<?php

class Core_Backend_Component_Subject_Controller_Content extends Dcmp_Component_Controller {

    public function indexAction($pageindex = 1, $pagesize = 20, $sort = 'modifiedtime', $dir = 'desc') {
        $this->getHistory()->record();
        $validator = $this->getRequest()->getValidator('filter');
        $collection = App::getModel('subject/collection_content')
                        ->pagination($pageindex, $pagesize)
                        ->joinAccount()
                        ->sortBy($sort, $dir);
        if ($validator->isNotEmpty('name')) {
            $collection->filterByTitle($validator->getValue('name'));
        }
        if ($validator->isNotEmpty('status')) {
            $collection->filterByStatus($validator->getValue('status'));
        }
        if ($validator->isNotEmpty('top')) {
            $collection->filterByTop($validator->getValue('top'));
        }
        if ($validator->isNotEmpty('new')) {
            $collection->filterByNew($validator->getValue('new'));
        }
        if ($validator->isNotEmpty('hot')) {
            $collection->filterByHot($validator->getValue('hot'));
        }
        if ($validator->isNotEmpty('tag')) {
            $collection->filterByTag($validator->getValue('tag'));
        }
        $collection->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'records' => $records));
    }

    public function createAction() {
        $videos = App::getModel('media/collection_video')->filterByStatus('published')->load();
        $categories = App::getModel('subject/collection_category')->load();
        $accounts = App::getModel('permission/collection_account')->filterByEnabled()->load();
        return $this->viewResult(array('categories' => $categories, 'accounts' => $accounts));
    }

    public function createPostAction() {
        $data = $this->getRequest()->getForm('content');
        $model = App::getModel('subject/content');
        $model->addData($data)->setStatus('draft');
        if (($errors = $model->validate() === TRUE)) {
            $model->save();
            $model->assignAccount($data['account_ids']);
            return $this->redirectResult($this->getUrl(NULL, 'index', 'subject', 'resource'));
        } else {
            $this->getMessager()->addError($this->__f('share.message.saveFail', '{subject.label.content}', $model->getName()))
                    ->addError($errors);
            return $this->createAction()->setModel($model);
        }
    }

    public function editAction($id) {
        $model = App::getModel('subject/content')->load($id);
        return $this->createAction()->setModel($model);
    }

    public function savePostAction() {
        return $this->saveModel('draft');
    }

    public function reviewAction($ids, $status, $statusmessage = ''){
        if($status == 'published'){
            App::getModel('subject/content')->publish($ids);
        }elseif($status == 'forbidden'){
            App::getModel('subject/content')->forbid($ids, $statusmessage);
        }
        return $this->redirectResult($this->getHistoryUrl('subject/content/index'));
    }    

    public function deleteAction($ids){
        App::getModel('subject/content')->deleteBatch($ids);
        return $this->redirectResult($this->getHistoryUrl('subject/content/index'));
    }

    public function generateTagAction() {
        $articles = App::getModel('subject/collection_content')->load();
        $tagModel = App::getModel('tag/keyword');
        $transaction = Kd_Db_Factory::getTransaction();
        try {
            $transaction->begin();
            foreach ($articles as $article) {
                $tags = explode(' ', $article->getTag());
                $tagModel->removeTagRecord($article->getId(), 'subject', $transaction)
                         ->addTagRecord($tags, $article->getId(), 'subject', $transaction);
            }
            $transaction->commit();
        } catch (Exception $ex) {
            $transaction->rollback();
            throw $ex;
        }
        $this->getMessager()->addInform($this->__f('share.message.success'));
        return $this->redirectResult($this->getHistoryUrl('subject/content/index'));
    }

    private function saveModel($state, $return = TRUE) {
        $data = $this->getRequest()->getForm('content');
        $model = App::getModel('subject/content');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data['info'])->addData($data)->setStatus($state);
        if(!isset($data['poi_ids'])){
            $model->setPoiIds(NULL);
        }
        if(!isset($data['industry_ids'])){
            $model->setIndustryIds(NULL);
        }
        if(!isset($data['recommend_poi_ids'])){
            $model->setRecommendPoiIds(NULL);
        }
        if(!isset($data['article_ids'])){
            $model->setArticleIds(NULL);
        }
        if(!isset($data['recommend_article_ids'])){
            $model->setRecommendArticleIds(NULL);
        }
        if(!isset($data['top_article_ids'])){
            $model->setTopArticleIds(NULL);
        }
        if(!isset($data['road_ids'])){
            $model->setRoadIds(NULL);
        }
        if(!isset($data['concessions_ids'])){
            $model->setConcessionsIds(NULL);
        }
        if(!isset($data['recommend_concessions_ids'])){
            $model->setRecommendConcessionsIds(NULL);
        }
        if(!isset($data['info']['video_ids'])){
            $model->setVideoIds(NULL);
        }
        if (($errors = $model->validate() === TRUE)) {
            $model->save();
            $this->getMessager()->addInform($this->__f('share.message.saveSuccess', '{subject.label.content}', $model->getName()));
            return $return ?
                    $this->redirectResult($this->getHistoryUrl('subject/content/index')) :
                    $this->redirectResult($this->getUrl(array('id' => $model->getIdValue()), 'edit'));
        } else {
            $this->getMessager()->addError($this->__f('share.message.saveFail', '{subject.label.content}', $model->getName()))
                    ->addError($errors);
            return $this->createAction()->setModel($model);
        }
    }

}